﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class AssetExport
{
    static string assetFilePath = ResourcesPath.LocalPath;
    static string configFilePath = ResourcesPath.LocalConfigPath;
    
    public static string GetSavePath(Object o)
    {
        string path = AssetDatabase.GetAssetPath(o);
        string savePath = path.Substring(7, path.Length - 7);
        savePath = savePath.Replace('.', '_');
        savePath += "_Dep.assetbunld";
        return savePath;
    }

    //[MenuItem("Assets/Resources Export")]
    public static void Export()
    {
        BuildAssetBundleOptions options =
                    BuildAssetBundleOptions.CollectDependencies |
                    BuildAssetBundleOptions.CompleteAssets |
                    BuildAssetBundleOptions.DeterministicAssetBundle;

        string savePath = assetFilePath + GetSavePath(Selection.activeGameObject);
        Directory.CreateDirectory(savePath.Substring(0, savePath.LastIndexOf('/')));
        UnityEditor.BuildPipeline.BuildAssetBundle(Selection.activeGameObject, null, savePath, options, GetBuildTarget());
    }

    //[MenuItem("Assets/TestExport")]
    public static void TestExport()
    {
        BuildAssetBundleOptions options =
                    BuildAssetBundleOptions.CollectDependencies |
                    BuildAssetBundleOptions.CompleteAssets |
                    BuildAssetBundleOptions.DeterministicAssetBundle;

        UnityEditor.BuildPipeline.PushAssetDependencies();
        foreach (Object o in Selection.objects)
        {
            string savePath = assetFilePath + GetSavePath(o);
            Directory.CreateDirectory(savePath.Substring(0, savePath.LastIndexOf('/')));
            UnityEditor.BuildPipeline.PushAssetDependencies();
            UnityEditor.BuildPipeline.BuildAssetBundle(o, null, savePath, options, GetBuildTarget());
        }

        foreach (Object o in Selection.objects)
        {
            UnityEditor.BuildPipeline.PopAssetDependencies();
        }
        
        UnityEditor.BuildPipeline.PopAssetDependencies();
    }

    public static BuildTarget GetBuildTarget()
    {
#if UNITY_IPHONE
        return BuildTarget.IPHONE;
#endif
#if UNITY_ANDROID
        return BuildTarget.Android;
#endif
#if UNITY_STANDALONE_WIN
        return BuildTarget.StandaloneWindows;
#endif
    }
}
